//
//  YQPayViewVC.m
//  KingRetail
//
//  Created by yuqin on 2019/6/26.
//  Copyright © 2019 yuqin. All rights reserved.
//

#import "YQPayViewVC.h"
#import "YQPayCell.h"
#import "YQPayModel.h"
#import "YQAddressListVC.h"
#import "YQConfirmPayBottomView.h"
#import "YQCheckGBKModel.h"

@interface YQPayViewVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *payTableView;
@property (nonatomic, strong) NSMutableArray *addressData;
@property (nonatomic, strong) YQConfirmPayBottomView *bottomView;
@property (nonatomic, strong) UIView *BackView;
@property (nonatomic, strong) UILabel *totalLab;
@property (nonatomic, strong) UIButton *paySoonBtn;
@property (nonatomic, strong) YQCheckGBKModel *checkModel;
@property (nonatomic, assign) BOOL isSelectCoupon;//是否使用了优惠券

//暂不启用
@property (nonatomic, strong) UILabel *nameAndTelLab;
@property (nonatomic, strong) UILabel *addressLab;

@end

@implementation YQPayViewVC
{
    BOOL _isHaveAddress;
//    NSString *_payPrice;//判断显示的价格与传的价格
    NSString *moneyGBKRate;
    NSString *gbkCnyRate;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.btnLeft setTitle:@"确认支付" forState:UIControlStateNormal];
    self.isSelectCoupon = YES;
    [self setupPayView];
    self.payTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //数据刷新
        [self loadAddressData];
    }];
    [self.payTableView.mj_header beginRefreshing];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(assignmentAddress:) name:@"NSNotficationSendDict" object:nil];
    
    
}

//修改地址
- (void)assignmentAddress:(NSNotification *)noti {
    
    YQPayModel *model = [YQPayModel mj_objectWithKeyValues:noti.userInfo];
    [self.addressData addObject:model];
    [self.payTableView reloadData];
}

- (NSMutableArray<NSDictionary *> *)addressData {
    if (!_addressData) {
        _addressData = [NSMutableArray array];
    }
    return _addressData;
}

- (void)loadAddressData {
    [self.addressData removeAllObjects];
    [SZHTTPSReqManager getRequestWithUrlString:YQ_joiningTogetherUrl(@"address/defaultAddr") appendParameters:nil successBlock:^(id responseObject) {
        BaseModel *base = [BaseModel modelWithJson:responseObject];
        if (base.code == 0) {
            self->_isHaveAddress = YES;
            YQPayModel *model = [YQPayModel mj_objectWithKeyValues:base.data];
            [self.addressData addObject:model];
        }else {
            //没有默认地址 则提示点击跳转页面
            self->_isHaveAddress = NO;
        }
        [self.payTableView reloadData];
        [self.payTableView.mj_header endRefreshing];
    } failureBlock:^(NSError *error) {
        [self.payTableView.mj_header endRefreshing];
    }];
}

- (void)setupPayView {
    [self.view addSubview:self.payTableView];
    [self.view addSubview:self.BackView];
    [self.BackView addSubview:self.totalLab];
    [self.BackView addSubview:self.paySoonBtn];
    
    
    [self.payTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(NavigationStatusBarHeight);
        make.size.mas_equalTo(CGSizeMake(ScreenWidth, ScreenHeight-NavigationStatusBarHeight-Botoom_IPhoneX-FIT(55)));
    }];
    
    [self.BackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.bottom.mas_equalTo(-Botoom_IPhoneX);
        make.size.mas_equalTo(CGSizeMake(ScreenWidth, FIT(55)));
    }];
    
    [self.totalLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(2*ScreenWidth/3.0, FIT(55)));
    }];
    
    [self.paySoonBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-kSpace);
        make.bottom.mas_equalTo(-FIT(12));
        make.size.mas_equalTo(CGSizeMake(ScreenWidth/3.0-FIT(16), FIT(32)));
    }];
}

- (UITableView *)payTableView {
    if (!_payTableView) {
        _payTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _payTableView.backgroundColor = MainBackgroundColor;
        _payTableView.delegate =self;
        _payTableView.dataSource = self;
        _payTableView.tableFooterView = self.bottomView;
        _payTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_payTableView registerNib:[UINib nibWithNibName:YQ_PayCell bundle:nil] forCellReuseIdentifier:YQ_PayCell];
    }
    return _payTableView;
}

- (YQConfirmPayBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[YQConfirmPayBottomView alloc] init];
        WeakSelf(self);
        _bottomView.priceLab.text = self.detailModel.price;
        if ([self.isWhole integerValue] == 1) {
            //市场价
            [_bottomView.mallIocn sd_setImageWithURL:[NSURL URLWithString:self.detailModel.goodImgUrl] placeholderImage:YQ_IMAGE(@"back_goods")];
            //点击改变底部的金额
            _bottomView.SelectUseGBKBlok = ^{
                
                if (weakSelf.bottomView.selectBtn.selected == YES) {
                    //选择了
                    weakSelf.isSelectCoupon = YES;
                }else {
                    weakSelf.isSelectCoupon = NO;
                }
                
                self.totalLab.text = [NSString stringWithFormat:@"共一件，合计：￥%@",self.detailModel.price];
                [self changeLabelTextWithLab];
            };
            
        }else {
            [_bottomView.selectBtn setHidden:YES];
            [_bottomView.mallIocn sd_setImageWithURL:[NSURL URLWithString:self.detailModel.goodImgUrl] placeholderImage:YQ_IMAGE(@"back_goods")];
        }
    }
    return _bottomView;
}
//富文本
- (void)changeLabelTextWithLab{
    NSArray *titleArr = [self.detailModel.price componentsSeparatedByString:@"."];
    _totalLab.attributedText = [AXAttributedString makeAttributedString:^(AXAttributedStringMaker *make) {
        make.text(@"共一件，").foregroundColor(UIColorFromRGB(0x808080)).font(YQ_Font(FIT(13))).underline(NSUnderlineStyleNone);
        make.text(@"合计：").foregroundColor(MainBlackColor).font(YQ_Font(FIT(14)));
        make.text(@"￥").foregroundColor(MainRedTextColor).font(YQ_Font(FIT(12)));
        make.text(titleArr[0]).foregroundColor(MainRedTextColor).font(YQ_Font(FIT(16)));
    }];
}

- (UIView *)BackView {
    if (!_BackView) {
        _BackView = [[UIView alloc] init];
        _BackView.backgroundColor = WhiteColor;
    }
    return _BackView;
}

- (UILabel *)totalLab {
    if (!_totalLab) {
        _totalLab = [YQViewFactory labelWithTextColor:MainRedTextColor textAlignment:NSTextAlignmentRight fontSize:kDescribeFont userBold:NO];
        [self changeLabelTextWithLab];
//        NSLog(@"_payPrice = %@",_payPrice);
    }
    return _totalLab;
}

- (UIButton *)paySoonBtn {
    if (!_paySoonBtn) {
        _paySoonBtn = [YQViewFactory buttonWithTitle:@"立即支付" titleColor:WhiteColor fontSize:kNormalButtonFont userBold:NO target:self sel:@selector(paySoonAction)];
        [_paySoonBtn setBackgroundImage:YQ_IMAGE(@"round_bg") forState:UIControlStateNormal];
    }
    return _paySoonBtn;
}

- (void)paySoonAction {
    if (isEmptyString(self.bottomView.tradingTF.text)) {
        [LCProgressHUD showFailure:@"请输入交易密码"];
        return;
    }
    
    if (_isHaveAddress == NO) {
        [LCProgressHUD showFailure:@"请设置收货地址"];
        return;
    }
    //
    YQPayModel *model = [self.addressData lastObject];
    //只有市场价能用GBK 批发价不能用
    NSDictionary *parameters;
//    NSLog(@"price = %@",_payPrice);
    if ([self.isWhole integerValue] == 1) {
        //市场价
        parameters = @{@"goodId":self.detailModel.goodId,
                       @"addressId":model.id,
                       @"quantity":@"1",
                       @"payprice":self.detailModel.price,
                       @"payGBKNum":@"",
                       @"couponNum":@"",
                       @"orderType":@"1",
                       @"payPassword":[AppUtil md5:self.bottomView.tradingTF.text]
                       };
    }else {
        //批发价
        parameters = @{@"goodId":self.detailModel.goodId,
                       @"addressId":model.id,
                       @"quantity":@"1",
                       @"payprice":self.detailModel.price,
                       @"payGBKNum":@"",
                       @"couponNum":@"1",
                       @"orderType":@"2",
                       @"payPassword":[AppUtil md5:self.bottomView.tradingTF.text]
                       };
    }
    
//    [LCProgressHUD showLoading:@"支付中..."];
    [SZHTTPSReqManager postRequestWithUrlString:YQ_joiningTogetherUrl(@"trade/goods/buyGood") appendParameters:nil bodyParameters:parameters successBlock:^(id responseObject) {
        if ([responseObject[@"code"] integerValue] == 0) {
//            [LCProgressHUD hide];
            [LCProgressHUD showSuccess:@"购买成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }else {
//            [LCProgressHUD hide];
            [LCProgressHUD showFailure:responseObject[@"msg"]];
        }
    } failureBlock:^(NSError *error) {
        
    }];
    
}

#pragma mark - 代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return FIT(65);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return FIT(250);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return section == 0? 0 : FIT(10);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YQPayCell *cell = [tableView dequeueReusableCellWithIdentifier:YQ_PayCell forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    self.nameAndTelLab = cell.nameAndTelLab;
    self.addressLab = cell.addressLab;
    if (_isHaveAddress == NO) {
        cell.nameAndTelLab.text = @"您还未设置收货地址";
        cell.addressLab.text = @"请点击设置收货地址";
    }else {
        YQPayModel *model = [self.addressData lastObject];
        cell.nameAndTelLab.text = [NSString stringWithFormat:@"%@ %@",model.name,model.phone];
        cell.addressLab.text = [NSString stringWithFormat:@"%@",model.addressDetail];
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return self.bottomView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    YQ_PUSH([YQAddressListVC new]);
}

@end
